package com.itheima.tilas.aspect;

import com.alibaba.fastjson.JSONObject;
import com.itheima.tilas.Utils.JwtUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * 统计接口耗时切面/逻辑
 *
 * @author 132
 */
@Slf4j
@Component
@Aspect
public class CountTimeAspect {
    @Resource
    HttpServletRequest request;
    @Around("execution(* com.itheima.tilas.service.impl.*.*(..))")
    public Object count(ProceedingJoinPoint point) {
        String token = request.getHeader("token");
        if(Objects.nonNull(token)){
            //获取操作人
            log.info("获取token{}",token);
            JSONObject jsonObject = JwtUtil.verifyToken(token);
            String username = jsonObject.getString("username");
            log.info("操作人{}",username);
        }
        //获取参数
        Object[] args = point.getArgs();
        log.info("请求参数{}", args);
        //获取类名
        Object target = point.getTarget();
        long start = System.currentTimeMillis();
        //执行父类方法
        try {
            Object proceed = point.proceed();
            //获取返回值
            log.info("获取返回值{}",proceed);
            long end = System.currentTimeMillis() - start;
            //point.getSignature().getName() 获取方法名
            log.info("{}执行时间为{}", point.getSignature().getName(), end);
            return proceed;
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }
    }
}
